/*
 * Copyright (c) 2009 the original author or authors
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package com.as3undohistory.register
{
	import as3reflect.Accessor;
	import as3reflect.IMetaDataContainer;
	import as3reflect.MetaData;
	import as3reflect.Type;
	
	import com.as3undohistory.manage.IPropertyValueStack;
	import com.as3undohistory.manage.PropertyValueStack;
	
	import flash.utils.Dictionary;
	import flash.utils.getDefinitionByName;
	import flash.utils.getQualifiedClassName;
	
	import mx.utils.StringUtil;
	
	/**
	 * @inheritDoc 
	 * @author Roland Zwaga
	 * 
	 */
	public class ObjectRegistration implements IObjectRegistration
	{
		private var _registeredClasses:Dictionary;
		
		/**
		 *  Constructs a new instance of ObjectRegistration
		 * 
		 */
		public function ObjectRegistration()
		{
			super();
			clear();
		}
		
		/**
		 *  
		 * @inheritDoc
		 * 
		 */
		public function clear():void
		{
			_registeredClasses = new Dictionary();
		}
		
		/**
		 *  
		 * @inheritDoc
		 * 
		 */
		public function registerClasses(classes:Array, accessorNamesList:Array=null):Array
		{
			if ((accessorNamesList != null) && (classes.length != accessorNamesList.length))
			{
				throw new Error("classes and accessorNamesList do not have the same length");
			}
			var undoClassRegistrations:Array = new Array();
			classes.forEach(function(item:Class,index:int,arr:Array):void
			{
				var accNameList:Array = (accessorNamesList != null) ? accessorNamesList[index] : null;
				undoClassRegistrations.push(registerClass(item,accNameList));
			});
			return undoClassRegistrations;
		}

		/**
		 * If the [Undoable] metadata is added to the class, this method will automatically add all accessors
		 * that have the appropriate [Bindable] metadata. It will only throw a 'not bindable' error when the [Undoable]
		 * tag is added to seperate accessors.
		 * @inheritDoc
		 * 
		 */
		public function registerClass(clazz:Class, accessorNames:Array=null):IUndoClassRegistration
		{
			var type:Type = Type.forClass(clazz);
			var accessorRegistrations:Array = new Array();
			if (hasUndoableMetadata(type) == false)
			{
				type.accessors.forEach(function(item:Accessor,index:int,arr:Array):void
				{
					if (hasUndoableMetadata(item) || nameIsInProvidedList(accessorNames,item.name))
					{
						if (alreadyRegistered(accessorRegistrations,item.name) == false)
						{
							accessorRegistrations.push(createAccessorRegistration(item));
						}
					}
				});
			}
			else
			{
				type.accessors.forEach(function(item:Accessor,index:int,arr:Array):void
				{
					if (alreadyRegistered(accessorRegistrations,item.name) == false)
					{
						var accReg:IAccessorRegistration = createAccessorRegistration(item,false);
						if (accReg != null)
						{
							accessorRegistrations.push(accReg);
						}
					}
				});
			}
			var undoClassRegistration:IUndoClassRegistration = new UndoClassRegistration(clazz,accessorRegistrations);
			_registeredClasses[clazz] = undoClassRegistration;
			return undoClassRegistration;
		}
		
		/**
		 *  
		 * @inheritDoc
		 * 
		 */
		public function isClassRegistered(clazz:Class):Boolean
		{
			return (_registeredClasses[clazz] != null);
		}
		
		/**
		 *  
		 * @inheritDoc
		 * 
		 */
		public function registerInstance(instance:Object):Array
		{
			var cls:Class = getDefinitionByName(getQualifiedClassName(instance)) as Class;
			var clsRegistration:IUndoClassRegistration = _registeredClasses[cls];
			var result:Array = new Array();
			clsRegistration.accessorRegistrations.forEach(function(item:IAccessorRegistration,index:int,arr:Array):void
			{
				var propStack:IPropertyValueStack = new PropertyValueStack(instance,item,instance[item.accessorName]);
				result.push(propStack);
			});
			return result;
		}
		
		/**
		 *  
		 * @inheritDoc
		 * 
		 */
		public function unregisterClass(clazz:Class):void
		{
			_registeredClasses[clazz] = null;
			delete _registeredClasses[clazz];
		}
		
		private function alreadyRegistered(accessorRegistrationList:Array,accessorName:String):Boolean
		{
			return accessorRegistrationList.some(function(item:IAccessorRegistration,index:int,arr:Array):Boolean
			{
				return (item.accessorName == accessorName);
			});
		}
		
		private function nameIsInProvidedList(nameList:Array,accessorName:String):Boolean
		{
			if (nameList != null)
			{
				return (nameList.indexOf(accessorName) > -1);
			}
			return false;
		}
		
		private function hasUndoableMetadata(metaDataContainer:IMetaDataContainer):Boolean
		{
			return metaDataContainer.hasMetaData("Undoable");
		}

		private function createAccessorRegistration(accessor:Accessor, throwError:Boolean=true):IAccessorRegistration
		{
			if (accessor.hasMetaData("Bindable"))
			{
				var arr:Array = accessor.getMetaData("Bindable");
				var metaData:MetaData = arr[0] as MetaData;
				var eventName:String = "";
				if (metaData.hasArgumentWithKey("event"))
				{
					eventName = metaData.getArgument("event").value;
					return new AccessorRegistration(eventName,accessor.name); 
				}
				//its allowed to omit the keyname, so check if there's an argument with an empty key, then assume this is the one we need:
				else if (metaData.hasArgumentWithKey(""))
				{
					eventName = metaData.getArgument("").value;
					return new AccessorRegistration(eventName,accessor.name); 
				}
				else
				{
					throw new Error(StringUtil.substitute("Property {0}'s Bindable metadata does not have an event key",accessor.name));
				}
			}
			else
			{
				if (throwError)
				{
					throw new Error(StringUtil.substitute("Property {0} is not bindable",accessor.name));
				}
			}
			return null;
		}
		
	}
}